#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::init(void)
{
    setFixedSize(1280,800);

    shell = new QShell(this);

    shell->setParent(this);
    shell->setText("hello");
    shell->move(200,80);
    shell->setFixedSize(800,600);


    serial = new QSerialPort;

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(30);

    serialInit();
}

void MainWindow::serialInit(void)
{
    serialList     = new QComboBox(this);
    serialBuadrate = new QLineEdit(this);
    serialConnect  = new QPushButton(this);

    serialList->move(10,770);
    serialList->setEditable(true);
    serialList->setFixedWidth(200);
    serialList->setFixedHeight(20);

    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
        //serialList->addItem(info.portName() + "   " + info.description(),NULL);
        serialList->addItem(info.portName(),0);
    }
    serialBuadrate->move(220,770);
    serialBuadrate->setText("115200");
    serialBuadrate->setFixedWidth(200);
    serialBuadrate->setFixedHeight(20);

    serialConnect->setText("connect");
    serialConnect->move(430,770);
    serialConnect->setFixedWidth(100);
    serialConnect->setFixedHeight(20);

    connect(serialConnect,SIGNAL(clicked()),this,SLOT(connec_serial()));
}



void MainWindow::update(void)
{
    int len;
    char buf[128];

    if(serial->isOpen()){
        len = serial->read(buf,128);

        if(len > 0){
            buf[len] = 0;
            shell->moveCursor(QTextCursor::End);
            shell->insertPlainText(QString(buf));
        }
    }

}

void MainWindow::connec_serial(void)
{
    QString s;

    s += serialBuadrate->text() + "\r\n";
    s += serialList->currentText() + "\r\n";

    shell->setText(s);

    if(serial->isOpen()){
        serialConnect->setText("connect");
        serial->close();
        return;
    }

    serial->setPortName(serialList->currentText());
    if(!serial->open(QIODevice::ReadWrite)){
        qDebug()<<serialList->currentText()<<" open failed!";
    }

    serial->setBaudRate(serialBuadrate->text().toInt(),QSerialPort::AllDirections);
    serial->setDataBits(QSerialPort::Data8);		//数据位为8位
    serial->setFlowControl(QSerialPort::NoFlowControl);//无流控制
    serial->setParity(QSerialPort::NoParity);	//无校验位
    serial->setStopBits(QSerialPort::OneStop); //一位停止位

    shell->setSerial(serial);
    serialConnect->setText("disconnect");
}


void QShell::keyPressEvent(QKeyEvent *event)
{
    QChar *c = event->text().data();
    char cc =  c->toLatin1();

    qDebug("c:%d\r\n",cc);

    if(serial != NULL){
        if(serial->isOpen()){
            serial->write(&cc,1);
        }
    }
}
